package com.flyan.game.motafx.component.npc;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import com.almasb.fxgl.core.util.LazyValue;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.entity.component.Component;
import com.almasb.fxgl.physics.BoundingShape;
import com.almasb.fxgl.physics.HitBox;
import com.almasb.fxgl.texture.AnimatedTexture;
import com.flyan.game.motafx.config.GameConfig;
import com.flyan.game.motafx.core.enums.EntityTypeEnum;
import com.flyan.game.motafx.core.util.animate.StillAnimateTable;
import com.flyan.game.motafx.core.util.entity.EntityUtils;
import com.flyan.game.motafx.effect.BaseEffect;
import com.flyan.game.motafx.entity.npc.NpcEntityInfo;
import javafx.util.Duration;

/**
 * npc 组件
 *
 * @author flyan
 * @version 1.0
 * @email flyan_by_chenu@sina.com
 * @since 2025/2/8
 */
public class NpcComponent extends Component {

    private AnimatedTexture atView;

    /**
     * npc 动画
     */
    private LazyValue<StillAnimateTable> animateTable = new LazyValue<>(() -> new StillAnimateTable(
            FXGL.image("materials/npcs.png"), 2,
            GameConfig.GRID_SIZE, GameConfig.GRID_SIZE,
            Duration.seconds(0.75)));

    public NpcComponent() {

    }

    @Override
    public void onAdded() {
        /* 根据类型渲染动画 */
        EntityTypeEnum type = (EntityTypeEnum) entity.getType();
        atView = new AnimatedTexture(animateTable.get().get(type.getType()));

        /* 挂载并播放动画 */
        entity.getViewComponent().addChild(atView);
        entity.getBoundingBoxComponent().addHitBox(new HitBox(BoundingShape.box(
                GameConfig.GRID_BBOX_SIZE, GameConfig.GRID_BBOX_SIZE)));
        atView.loop();
    }

    /**
     * 互动
     *
     * @param other 参与互动的其他实体
     */
    public void interact(Entity other) {
        /* 角色可以和 npc 交互 */
        if (other.getType() == EntityTypeEnum.CHARACTER_BRAVE) {
            NpcEntityInfo npcInfo = EntityUtils.getEntityInfo(entity, NpcEntityInfo.class);
            /* 触发交互效果 */
            if (CollUtil.isNotEmpty(npcInfo.getEffects())) {
                npcInfo.getEffects().forEach(it -> {
                    BaseEffect effect = ReflectUtil.newInstance(it);
                    effect.setTriggerEntity(entity);
                    effect.apply(other);
                });
            }
        }
    }

}
